<?php
namespace app\admin\model;

class AdminUser extends \think\Model{

    protected $table = "admin_user";
    /**
     * 判断是否登录
     * 如果有cookie值， 则自动登录
     * @return true or false
     */
    public function isLogin(){
        //t($_COOKIE);
        if( !session('?admin_user_id') ){
            $id = cookie('admin_user_id');
            if( $id ){
                $rs = self::get($id);
                $session = [
                    'admin_user_id'             =>  $rs->id,
                    'admin_username'            =>  $rs->username,
                    'admin_user_last_login_ip'  =>  $rs->last_login_ip,
                    'admin_user_last_login_time'=>  $rs->last_login_time,
                    'admin_user_login_times'    =>  $rs->login_times,
                ];
                foreach($session as $k => $v){
                    session($k,$v);
                }
                return true;
            }
            return false;
        }
        return true;
    }
    
    /**
     * 用户登录
     * @param unknown $username 用户名
     * @param unknown $password 密码
     * @param unknown $is_remember   记住登录
     * @return true or false
     */
    public function logIn($username, $password, $is_remember = false){
        //查询
        $rs = self::where('username', $username)->find();
        
        //判断
        if($rs==false)
            return com_error(['username'=>'用户名不存在！']);
        
        $pass = com_password($password);
        if( $pass != $rs['password'])
            return com_error(['password'=>'密码错误！']);
        
        //登录成功
        $session = [
            'admin_user_id'             =>  $rs['id'],
            'admin_username'            =>  $rs['username'],
            'admin_user_last_login_ip'  =>  $rs['last_login_ip'],
            'admin_user_last_login_time'=>  $rs['last_login_time'],
            'admin_user_login_times'    =>  $rs['login_times'],
        ];
        foreach($session as $k => $v){
            session($k,$v);
        }
        
        if( $is_remember ){
            $cookie_time = 3600*24*c('cookie_day');
            cookie('admin_user_id', $rs['id'], ['expire' => $cookie_time]);
        }        
        
        $data = [
            "id"              => $rs['id'],
            "last_login_time" => time(),
            "last_login_ip"   => com_client_ip(),
            "login_times"     => $rs['login_times']+1,
            "error_times"     => 0,
        ];
        self::update($data);
        return true;
    }
    
    /**
     * 退出登录
     * 清楚cookie和session
     */
    public function logOut(){
        \think\Session::clear();
        \think\Cookie::delete('admin_user_id');
        \think\Cookie::delete('deny_urls');
        \think\Cookie::delete('menu');
    }
}